package com.shengdou.as.slopsapptest.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.shengdou.as.slopsapptest.Fragment.CheckFragment;
import com.shengdou.as.slopsapptest.Fragment.MyFragment;
import com.shengdou.as.slopsapptest.Fragment.NotesFragment;
import com.shengdou.as.slopsapptest.Fragment.PoolTabFragment;
import com.shengdou.as.slopsapptest.R;
import com.shengdou.as.slopsapptest.utils.Constants;
import com.shengdou.as.slopsapptest.utils.FileUtils;
import com.shengdou.as.slopsapptest.utils.HttpUtils;
import com.shengdou.as.slopsapptest.utils.LogUtil;
import com.shengdou.as.slopsapptest.utils.SharedPreferenceUtil;
import com.shengdou.as.slopsapptest.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;


public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    private String alias = "";
    private CheckFragment mCheckFragment;
    private PoolTabFragment mPoolTabFragment;
    private NotesFragment mNotesFragment;
    private MyFragment myFragment;
    private RadioGroup group;
    private RadioButton RadioCheck;
    private Map<String, String> params = new HashMap<>();
    private String status = "";//新版本路径
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 5;//调用写入权限
    private boolean select;//判断是否开启权限
    private String versionName;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.VERSION:
                    //获取版本信息
                    String data = msg.obj.toString();
                    LogUtil.e("获取版本信息", data);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(data);
                        status = jsonObject.getString("download");
                        LogUtil.e("获取版本路径", status);
                        String version = jsonObject.getString("version");

                        if (Float.parseFloat(version) > Float.parseFloat(versionName)) {
                            requestWritePermission();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        alias = SharedPreferenceUtil.getPreferenceString(MainActivity.this, "alias");
        if (alias != null && !alias.equals("")) {
            //设置别名Alia
            JPushInterface.setAlias(this, 0, alias);
        }
        init();
    }

    public static void exit() {
        MainActivity activity = new MainActivity();
        activity.finish();
    }

    //设置写入权限
    private void requestWritePermission() {
        int hasWriteContactsPermission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteContactsPermission
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
            return;
        } else {
            select = FileUtils.avaiableMedia();
            showUpdateDialog();
        }
    }

    private void showUpdateDialog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.show();
        alertDialog.getWindow().setContentView(R.layout.alert_dialog_base);
        alertDialog.getWindow().findViewById(R.id.dialog_verify_cancle).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.cancel();
            }
        });
        alertDialog.getWindow().findViewById(R.id.dialog_verify_go).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!status.equals("")) {
                    if (select == true) {
                        HttpUtils.inProgress(MainActivity.this, status, Environment.getExternalStorageDirectory().getAbsolutePath());
                    } else {
//                        HttpUtils.inProgress(MainActivity.this, status, MainActivity.this.getFilesDir().getAbsolutePath());
//                        ToastUtils.showToast("sd卡权限未开！不能更新版本");
                        Uri uri = Uri.parse(status);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        startActivity(intent);
                    }
                }
                alertDialog.dismiss();
            }
        });
    }


    private void init() {
        SharedPreferenceUtil.savePreferenceBoolean(MainActivity.this, "playSelect", true);
        group = (RadioGroup) findViewById(R.id.tab);
        RadioCheck = (RadioButton) findViewById(R.id.btn_check);
        RadioCheck.setOnClickListener(this);
        group.setOnCheckedChangeListener(this);
        // 设置默认的Fragment
        setDefaultFragment();
        checkUploadData();
    }

    private void setDefaultFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mCheckFragment = new CheckFragment();
        transaction.replace(R.id.fragment_container, mCheckFragment);
        transaction.commit();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        switch (checkedId) {
          /*  case R.id.btn_check:
                mCheckFragment = null;
                if (mCheckFragment == null) {
                    mCheckFragment = new CheckFragment();
                }
                transaction.replace(R.id.fragment_container, mCheckFragment);


                break;*/
            case R.id.btn_notes:
                if (mNotesFragment == null) {
                    mNotesFragment = new NotesFragment();
                }
                transaction.replace(R.id.fragment_container, mNotesFragment);
                break;
            case R.id.btn_center:
                if (myFragment == null) {
                    myFragment = new MyFragment();
                }
                transaction.replace(R.id.fragment_container, myFragment);

                break;
        }
        transaction.commit();

    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                SharedPreferenceUtil.savePreferenceFloat(MainActivity.this, "newHeight", 3.5f);
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_check) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            mCheckFragment = null;
            if (mCheckFragment == null) {
                mCheckFragment = new CheckFragment();
            }
            transaction.replace(R.id.fragment_container, mCheckFragment);
            transaction.commit();
        }
    }

    int versionCurrent;

    // 检查版本更新
    private void checkUploadData() {

        PackageManager manager = getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
            versionCurrent = info.versionCode;
            versionName = info.versionName;
            SharedPreferenceUtil.savePreferenceString(MainActivity.this, "versionName", versionName);
            params.put("client", "Android");
            params.put("version", info.versionName);
//            HttpUtils.postParmas(mHandler, NetConstant.VERSION, params, Constants.VERSION, MainActivity.this);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                if (fragment != null) {
                    fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
                }
            }
        }
        switch (requestCode) {
            case WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        select = FileUtils.avaiableMedia();
                        showUpdateDialog();
                    } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        select = false;
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            ToastUtils.showToast("您已禁止询问sd卡权限...");
                        } else {
                            ToastUtils.showToast("没有设置权限");
                        }
                        showUpdateDialog();
                    }
                }
                break;
        }
    }
}
